import React, { ReactElement, useContext } from 'react';
import { Text, View } from 'react-native';
import moment from 'moment';

import CustomText from '../../../../../../components/Text';

import styles from './style';
import { Store } from '../../reducer';
import Button from '../../../../../../components/Button';
import { setCurrentDate } from '../../actions';
import { Calender } from '../../types';

const WEEK = ['日', '一', '二', '三', '四', '五', '六'];

const MONTH = [
  '一月',
  '二月',
  '三月',
  '四月',
  '五月',
  '六月',
  '七月',
  '八月',
  '九月',
  '十月',
  '十一月',
  '十二月'
];

export default (): ReactElement => {
  const { state } = useContext(Store);
  const { currentDate, data } = state;
  const { lessons = [] } = data;
  const days: Calender[] = [
    moment().subtract(3, 'days'),
    moment().subtract(2, 'days'),
    moment().subtract(1, 'days'),
    moment(),
    moment().add(1, 'days'),
    moment().add(2, 'days'),
    moment().add(3, 'days')
  ].map(
    (item): Calender => {
      const today = moment().format('DD');
      const week = WEEK[item.day()];
      const day = item.format('DD');
      const month = item.format('M');
      const dayDesc = day === '01' ? MONTH[Number(month) - 1] : day;
      const date = item.format('YYYY-MM-DD');

      const haveCourse = !!lessons.find(
        (lesson): boolean =>
          moment(lesson.startTime).format('YYYY-MM-DD') === date
      );
      return {
        week: day === today ? '今' : week,
        weekDetail: day === today ? '今日' : `星期${week}`,
        day: dayDesc,
        date,
        haveCourse
      };
    }
  );
  return (
    <View style={styles.container}>
      {days.map(
        (item): ReactElement => {
          const { week, day, date, haveCourse } = item;
          const selected = date === currentDate.date;
          return (
            <Button
              key={item.weekDetail}
              style={[styles.item, selected ? styles.selected : {}]}
              onPress={(): void => {
                setCurrentDate(item);
              }}
            >
              <CustomText
                style={[styles.week, selected && styles.selectedWeek]}
              >
                {week}
              </CustomText>
              <Text
                style={[
                  styles.day,
                  day === '十一月' || day === '十二月' ? styles.month : {}
                ]}
              >
                {day}
              </Text>
              {haveCourse && !selected ? <View style={styles.circle} /> : null}
            </Button>
          );
        }
      )}
    </View>
  );
};
